import os
# os.environ["DJANGO_SETTINGS_MODULE"] = "dailyfresh.settings"
# import django
# django.setup()
from celery import Celery
from django.core.mail import send_mail
from django.conf import settings
from django.template import loader
from goods.models import GoodsCategory, IndexCategoryGoodsBanner, IndexGoodsBanner, IndexPromotionBanner


# 创建celery应用对象
app = Celery('celery_tasks.tasks_list', broker='redis://192.168.204.135:6379/4')


@app.task
def send_active_email(to_mail, user_name, token):
    """封装发送邮件方法"""
    subject = "天天生鲜用户激活"  # 标题
    body = ''  # 文本邮件体
    sender = settings.EMAIL_FROM   # 发件人
    receiver = [to_mail]  # 收件人
    html_body = '<h1>尊敬的用户 %s, 感谢您注册天天生鲜！</h1>' \
                '<br/><p>请点击此链接激活您的帐号<a href="http://127.0.0.1:8000/users/active/%s">' \
                'http://127.0.0.1:8000/users/active/%s</a></p>' % (user_name, token, token)
    send_mail(subject, body, sender, receiver, html_message=html_body)


@app.task
def generate_static_index_html():
    """生成静态的html页面"""

    print(1545)
    # 全部商品分类
    categories = GoodsCategory.objects.all()

    # 轮播图展示栏
    banners = IndexGoodsBanner.objects.all().order_by('index')

    # 推广商品展示栏
    promotions = IndexPromotionBanner.objects.all().order_by('index')

    # 具体商品列表
    # 根据category查询商品
    for category in categories:
        title_banners = IndexCategoryGoodsBanner.objects.filter(
            category=category).filter(display_type=0).order_by('index')
        category.title_banners = title_banners
        # 通过给实例化对象添加属性的方式传递
        image_banners = IndexCategoryGoodsBanner.objects.filter(category=category, display_type=1).order_by('index')
        category.image_banners = image_banners[0:4]

    # 购物车信息
    cart_num = 0
    context = {
        'categories': categories,
        'banners': banners,
        'promotions': promotions,
        'cart_num': cart_num,
    }
#   # 加载模板

    template = loader.get_template('static_index.html')
    html_data = template.render(context)

    # 保存成html文件： 放到静态文件按中
    file_path = os.path.join(settings.STATICFILES_DIRS[0], 'index.html')
    with open(file_path, 'w') as file:
        file.write(html_data)








